package com.ming.springboot.data;

import com.ming.springboot.util.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created by mqsi on 2022/5/15 19:18
 */
@ControllerAdvice(basePackages = "com.ming.springboot.controller")
public class ResponseHandler implements ResponseBodyAdvice<Object> {
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if (body instanceof String){
			return JsonUtil.objectToJson(Result.success(body));
		} else if (body instanceof ErrorResult){
			ErrorResult errorResult = (ErrorResult) body;
			return Result.fail(errorResult.getResultCode(), errorResult.getMessage());
		} else if (body instanceof Result){
			return body;
		}
		return Result.success(body);
	}
}
